import React, { useState, useEffect } from 'react';
import { BasicSettings as BasicSettingsType, validateBasicSettings } from './SettingsTypes';

interface BasicSettingsProps {
  initialSettings: BasicSettingsType;
  onSettingsChange: (settings: BasicSettingsType) => void;
}

const BasicSettings: React.FC<BasicSettingsProps> = ({ initialSettings, onSettingsChange }) => {
  const [settings, setSettings] = useState<BasicSettingsType>(initialSettings);
  const [errors, setErrors] = useState<{ [key: string]: string }>({});
  const [isDirty, setIsDirty] = useState(false);

  // 初始化设置
  useEffect(() => {
    setSettings(initialSettings);
    setIsDirty(false);
    setErrors({});
  }, [initialSettings]);

  // 处理文本输入变化
  const handleTextChange = (field: keyof BasicSettingsType, value: string | number | boolean) => {
    setIsDirty(true);
    setSettings(prev => ({ ...prev, [field]: value }));
    
    // 清除相关错误
    if (errors[field as string]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field as string];
        return newErrors;
      });
    }
  };

  // 处理保存
  const handleSave = () => {
    const validationErrors = validateBasicSettings(settings);
    if (Object.keys(validationErrors).length === 0) {
      const updatedSettings = {
        ...settings,
        lastUpdated: new Date().toISOString()
      };
      
      onSettingsChange(updatedSettings);
      
      // 保存到本地存储
      localStorage.setItem('basicSettings', JSON.stringify(updatedSettings));
      
      setIsDirty(false);
      alert('基础设置已成功保存！');
    } else {
      setErrors(validationErrors);
    }
  };

  // 处理重置
  const handleReset = () => {
    setSettings(initialSettings);
    setErrors({});
    setIsDirty(false);
  };

  return (
    <div className="basic-settings">
      <h2>基础设置</h2>
      
      <div className="settings-section">
        <h3>服务器设置</h3>
        
        <div className="setting-group">
          <label className="setting-label">
            服务器地址 <span className="required">*</span>
          </label>
          <input
            type="text"
            value={settings.serverUrl}
            onChange={(e) => handleTextChange('serverUrl', e.target.value)}
            className={`setting-input ${errors.serverUrl ? 'error' : ''}`}
            placeholder="https://api.example.com"
          />
          {errors.serverUrl && <span className="error-message">{errors.serverUrl}</span>}
          <p className="setting-description">API服务器的基础URL地址</p>
        </div>

        <div className="setting-group">
          <label className="setting-label">
            API超时时间（秒） <span className="required">*</span>
          </label>
          <input
            type="number"
            value={settings.apiTimeout}
            onChange={(e) => handleTextChange('apiTimeout', parseInt(e.target.value) || 0)}
            className={`setting-input ${errors.apiTimeout ? 'error' : ''}`}
            min="1"
            max="300"
          />
          {errors.apiTimeout && <span className="error-message">{errors.apiTimeout}</span>}
          <p className="setting-description">API请求的最大等待时间</p>
        </div>
      </div>

      <div className="settings-section">
        <h3>性能与存储</h3>
        
        <div className="setting-group">
          <label className="setting-label">自动保存间隔（秒）</label>
          <input
            type="number"
            value={settings.autoSaveInterval}
            onChange={(e) => handleTextChange('autoSaveInterval', parseInt(e.target.value) || 0)}
            className={`setting-input ${errors.autoSaveInterval ? 'error' : ''}`}
            min="0"
            max="300"
          />
          {errors.autoSaveInterval && <span className="error-message">{errors.autoSaveInterval}</span>}
          <p className="setting-description">设置为0禁用自动保存</p>
        </div>

        <div className="setting-group">
          <label className="setting-label">缓存大小（MB）</label>
          <input
            type="number"
            value={settings.cacheSize}
            onChange={(e) => handleTextChange('cacheSize', parseInt(e.target.value) || 0)}
            className={`setting-input ${errors.cacheSize ? 'error' : ''}`}
            min="0"
            max="4096"
          />
          {errors.cacheSize && <span className="error-message">{errors.cacheSize}</span>}
          <p className="setting-description">本地缓存的最大容量</p>
        </div>
      </div>

      <div className="settings-section">
        <h3>系统行为</h3>
        
        <div className="setting-group">
          <label className="setting-checkbox-label">
            <input
              type="checkbox"
              checked={settings.enableLogging}
              onChange={(e) => handleTextChange('enableLogging', e.target.checked)}
            />
            <span>启用日志记录</span>
          </label>
          <p className="setting-description">记录系统操作日志以便于故障排查</p>
        </div>

        <div className="setting-group">
          <label className="setting-checkbox-label">
            <input
              type="checkbox"
              checked={settings.debugMode}
              onChange={(e) => handleTextChange('debugMode', e.target.checked)}
            />
            <span>启用调试模式</span>
          </label>
          <p className="setting-description">显示详细的调试信息和错误报告</p>
        </div>

        <div className="setting-group">
          <label className="setting-checkbox-label">
            <input
              type="checkbox"
              checked={settings.notificationSound}
              onChange={(e) => handleTextChange('notificationSound', e.target.checked)}
            />
            <span>启用通知声音</span>
          </label>
          <p className="setting-description">收到新通知时播放声音提醒</p>
        </div>
      </div>

      <div className="settings-actions">
        <button
          type="button"
          className="btn-reset"
          onClick={handleReset}
          disabled={!isDirty}
        >
          重置
        </button>
        <button
          type="button"
          className="btn-save"
          onClick={handleSave}
          disabled={Object.keys(errors).length > 0 || !isDirty}
        >
          保存设置
        </button>
      </div>

      <div className="settings-note">
        <p>注意事项：</p>
        <p>• 服务器地址和API超时时间为必填项</p>
        <p>• 某些设置可能需要刷新页面才能生效</p>
        <p>• 基础设置将保存在本地浏览器中，更换设备或清除缓存后需要重新设置</p>
        <p>• 在调试模式下可能会显示敏感信息，请在生产环境中禁用</p>
      </div>
    </div>
  );
};

export default BasicSettings;